import objectUtils from "@/utils/object/index.js";

export default objectUtils.freeze({
	verify: function(idCard = "") {
		if (Object.prototype.toString.call(idCard) !== "[object String]") {
			return false;
		}
		if (idCard.length !== 18 && idCard.length !== 16) {
			return false;
		}
		let year = +idCard.slice(6, 10);
		if (year < 1913 || year > new Date().getFullYear()) {
			return false;
		}
		let month = +idCard.slice(10, 12);
		if (month < 1 || month > 12) {
			return false;
		}
		let day = +idCard.slice(12, 14);
		let days = 0;
		if ([4, 6, 9, 11].indexOf(month) !== -1) {
			days = 30;
		} else if ([1, 3, 5, 7, 8, 10, 12].indexOf(month) !== -1) {
			days = 31;
		} else if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
			days = 29;
		} else {
			days = 28;
		}
		if (day < 1 || day > days) {
			return false;
		}
		if (/^(\d|X)$/.test(idCard.slice(17, 18)) === false) {
			return false;
		}
		let ratio = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		let match = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
		let top17CharArr = idCard.slice(0, 17).split('');
		let count = 0;
		for (let i = 0; i < top17CharArr.length; i++) {
			if (isNaN(+top17CharArr[i])) {
				return false;
			}
			count += +top17CharArr[i] * ratio[i];
		}
		if (match[count % 11] !== idCard.slice(17, 18)) {
			return false;
		}
		return true;
	},
	info: function(idCard = "") {
		const info = {};
		if (this.verify(idCard)) {
			let year = +idCard.slice(6, 10);
			let month = +idCard.slice(10, 12);
			let date = +idCard.slice(12, 14);
			let curDate = new Date();
			let curYear = curDate.getFullYear();
			let curMonth = curDate.getMonth() + 1;
			let curDay = curDate.getDate();
			try {
				if (curMonth < month || (curMonth === month && curDay < date)) {
					info.age = curYear - year - 1;
				} else {
					info.age = curYear - year;
				}
			} catch (e) {
				info.age = 0;
			}
			info.birthday = year + "-" + (month < 10 ? "0" + month : month) + "-" + (date < 10 ? "0" + date : date);
			info.sex = +idCard.slice(16, 17);
			info.sex = info.sex % 2 === 0 ? 0 : 1;
		}
		return info;
	}
});